/*
 * @Author: nengwu 409791297@qq.com
 * @Date: 2020-06-24 16:03:39
 * @LastEditors: mylesshie@gmail.com
 * @LastEditTime: 2020-09-12 23:00:13
 * @description:
 */
import React, { useState, useCallback, useEffect } from 'react'
import { StatusBar, Text, View, FlatList, Platform } from 'react-native'
import { useSelector, useDispatch } from 'react-redux'
import RNBootSplash from 'react-native-bootsplash'
import JPush from 'jpush-react-native'
import { useNavigation } from '@react-navigation/native'
import ScrollableTabView from 'react-native-scrollable-tab-view'
import EmptyList from '@/components/EmptyList'
import ScrollTabBar from '@/components/ScrollTabBar'
import IndexSwiper from '@/components/IndexSwiper'
import NewsItem from '@/components/NewsItem'
import HomeHeader from '@/components/HomeHeader'
import AgreePop from '@/components/AgreePop'

import * as mainActions from '../../actions/main'
import * as permissions from '@/libs/permission'
import styles from './styles'

const Home = props => {
  const columns = useSelector(state => state.main.columns.firstPage)
  const banners = useSelector(state => state.main.homeBanners)
  const dispatch = useDispatch()
  const navigation = useNavigation()

  const [articleList, setArticleList] = useState([])
  const [isRefreshing, setIsRefreshing] = useState(false)
  const [activeColumn, setActiveColumn] = useState(columns[0])
  const [activeColumnIndex, setActiveColumnIndex] = useState(0)
  // 存放对应栏目列表数据
  const [dataAry, setDataAry] = useState({})
  const [pageNum, setPageNum] = useState(1)
  const [pageEnd, setPageEnd] = useState(false)
  const [showAgreePop, setShowAgreePop] = useState(false)
  const pageSize = 20

  const _init = useCallback(() => {
    dispatch(mainActions.getColumns()).then(res => {
      setActiveColumn(res.firstPage[0])
      RNBootSplash.hide({ duration: 250 })
    })
  }, [dispatch])

  // 初始化
  useEffect(() => {
    _init()
    // 判断是否已读协议
    global.storage
      .load({
        key: 'agreement'
      })
      .then(ret => { })
      .catch(() => {
        setShowAgreePop(true)
        navigation.setOptions({
          tabBarVisible: false
        })
      })

    const _connectListener = result => {
      console.log('connectListener:' + JSON.stringify(result))
    }
    JPush.addConnectEventListener(_connectListener)
    //通知回调
    const _notificationListener = result => {
      console.log('notificationListener:' + JSON.stringify(result))
      if (result.extras && result.extras.toPage && result.extras.id) {
        navigation.navigate(result.extras.toPage, {
          id: result.extras.id
        })
      }
    }
    JPush.addNotificationListener(_notificationListener)
    //本地通知回调
    const _localNotificationListener = result => {
      console.log('localNotificationListener:' + JSON.stringify(result))
    }
    JPush.addLocalNotificationListener(_localNotificationListener)
    //自定义消息回调
    const _customMessageListener = result => {
      console.log('customMessageListener:' + JSON.stringify(result))
    }
    JPush.addCustomMessagegListener(_customMessageListener)
    //tag alias事件回调
    const _tagAliasListener = result => {
      console.log('tagAliasListener:' + JSON.stringify(result))
    }
    JPush.addTagAliasListener(_tagAliasListener)
    //手机号码事件回调
    const _mobileNumberListener = result => {
      console.log('mobileNumberListener:' + JSON.stringify(result))
    }
    JPush.addMobileNumberListener(_mobileNumberListener)
  }, [])

  useEffect(() => {
    if (isRefreshing && pageNum === 1) {
      dispatch(mainActions.getArtiles(activeColumn.id, pageNum, pageSize)).then(
        res => {
          if (Platform.OS === 'android') {
            permissions.requestStoragePermission()
          }
          setIsRefreshing(false)
        }
      )
    }
  }, [isRefreshing])



  // 栏目和页码变更时获取对应栏目/页码的新闻列表
  useEffect(() => {
    if (activeColumn.id) {
      dispatch(mainActions.getBanners())
      dispatch(mainActions.getArtiles(activeColumn.id, pageNum, pageSize)).then(
        res => {
          setIsRefreshing(false)
          let nowList = []
          if (pageNum === 1) {
            nowList = res.list
          } else {
            nowList = articleList.concat(res.list)
          }
          setArticleList(nowList)
          let nowDataAry = dataAry
          nowDataAry[activeColumn.id] = nowList
          setDataAry({
            ...nowDataAry
          })
          setPageEnd(res.total <= res.pageNum * res.pageSize)
        }
      )
    }
  }, [activeColumn, pageNum, pageSize])

  // 切换选项卡
  const _onChangeColumn = index => {
    if (activeColumnIndex === index.i) return
    setActiveColumn(columns[index.i])
    setActiveColumnIndex(index.i)
    setPageNum(1)
  }

  // 生成列表
  const _renderItem = ({ item }) => (
    <NewsItem
      id={item.id}
      title={item.title}
      coverImgs={item.coverUrl}
      type={item.artType}
      topping={item.topping}
    />
  )

  // 刷新
  const _onRefresh = () => {
    setPageNum(1)
    setIsRefreshing(true)
  }

  // 加载更多
  const _onLoadMore = () => {
    if (pageEnd) return
    setPageNum(pageNum + 1)
  }

  const _search = text => {
    dispatch(mainActions.doSearch(text)).then(res => {
      dataAry[activeColumn.id] = res
      setDataAry({
        ...dataAry
      })
    })
  }

  const _createSlide = () => {
    return columns.map((item, index) => {
      return (
        <View style={styles.slideWrap} key={index} tabLabel={item.colName}>
          <FlatList
            ListHeaderComponent={<IndexSwiper list={banners} />}
            data={dataAry[item.id]}
            renderItem={_renderItem}
            onRefresh={_onRefresh}
            refreshing={isRefreshing}
            onEndReached={_onLoadMore}
            keyExtractor={ite => ite.id + ite.title}
            ListEmptyComponent={<EmptyList />}
            ListFooterComponent={
              pageEnd ? (
                <View style={styles.pageEnd}>
                  <Text style={styles.pageEndText}>已经到底了～</Text>
                </View>
              ) : null
            }
          />
        </View>
      )
    })
  }

  useEffect(() => {
    // console.log('更新dataAry:', dataAry)
  }, [dataAry])

  const _onAgreePop = () => {
    global.storage
      .save({
        key: 'agreement',
        data: {
          isOk: true
        }
      })
      .then(() => {
        setShowAgreePop(false)
        navigation.setOptions({
          tabBarVisible: true
        })
      })
  }

  return (
    <>
      <StatusBar
        barStyle="dark-content"
        backgroundColor="transparent"
        translucent={true}
      />
      {showAgreePop ? <AgreePop onAgree={_onAgreePop} /> : null}
      <HomeHeader doSearch={_search} />
      <View style={styles.wrap}>
        <ScrollableTabView
          onChangeTab={_onChangeColumn}
          renderTabBar={() => <ScrollTabBar />}
        >
          {_createSlide()}
        </ScrollableTabView>
      </View>
    </>
  )
}

export default Home
